var bufferCallerCollection = {
    _bufferCallerList: [],
    add: function(fn, prjName) {
        var bufferCaller = bufferCallerCollection._findBufferCallerOrCreateOne(prjName);
        bufferCaller.add(fn);
    },
    stop: function(prjName) {
        var bufferCaller = bufferCallerCollection._findBufferCallerOrCreateOne(prjName);
        bufferCaller.stop();
    },
    _createOne: function(prjName) {
        var bufferCaller = {
            prjName: prjName,
            fnBuffer: [],
            callFn: function(fn) {
                var Q = require('q');
                var defer = Q.defer();
                try {
                    fn();
                } catch (err) {
                    console.log(err);
                }
                setTimeout(function() {
                    defer.resolve();
                }, 2800);
                return defer.promise;
            },
            running: false,
            callBuffer: function() {
                if (bufferCaller.fnBuffer.length === 0) {
                    bufferCaller.running = false;
                    return;
                }
                var fn = bufferCaller.fnBuffer[0];
                bufferCaller.callFn(fn).then(function() {
                    bufferCaller.fnBuffer.splice(0, 1);
                    bufferCaller.callBuffer();
                });
            },
            stop: function() {
                bufferCaller.fnBuffer.length = 0;
                bufferCaller.running = false;
            },
            add: function(fn) {
                bufferCaller.running = true;
                bufferCaller.fnBuffer.push(fn);
                if (bufferCaller.fnBuffer.length === 1) {
                    bufferCaller.callBuffer();
                }
            }
        };
        return bufferCaller;
    },
    _findBufferCallerOrCreateOne: function(prjName) {
        var buffer = null;
        for (var i = 0; i < bufferCallerCollection._bufferCallerList.length; i++) {
            if (bufferCallerCollection._bufferCallerList[i].prjName === prjName) {
                buffer = bufferCallerCollection._bufferCallerList[i];
            }
        }
        if (!buffer) {
            buffer = bufferCallerCollection._createOne(prjName);
            bufferCallerCollection._bufferCallerList.push(buffer);
        }
        return buffer;
    }
};





module.exports = bufferCallerCollection;
